<template>
  <div>
    <ListTable ref="RefListTable" :table-data="tableData" style="padding: 0px 20px 40px 20px;" :loading="tableLoading" :table-col="tableCol">
      <template slot="col1" slot-scope="scope">
        <el-button
          :loading="scope.row.loadingDel"
          size="mini"
          type="text"
          icon="el-icon-delete"
          style="color: red; margin-left: 0px; margin-right: 10px; padding-top: 0px; padding-bottom: 0px;"
          @click="handleRowDel(scope.row)"
        >手动清理</el-button>
      </template>
    </ListTable>
  </div>
</template>
<script>
  import { parseTime } from '@/utils'
  import listMixin from '@/mixins/list'
  import { mapGetters } from 'vuex'
  import { realtimeLocation, clearPeople } from '@/api/api'
  export default {
    mixins: [listMixin],
    data() {
      return {
        timeId: '',
        isTimer: false,
        listTitle: [
          'carId',
          'car.carType',
          'car.RFID',
          'car.plateNumber',
          'baseStation.area.name',
          'autoGate.area.name',
          'autoGate.name',
          'enterTime',
          'updateTime',
          'id'
        ],
        // 列表数据
        tableData: [],
        // 列表表头
        tableCol: [
          { type: 'index', label: '序号', width: '60px', height: '250' },
          {
            label: '车辆类型',
            formatter(row, col, cell) {
              let deptName = ''
              if (row.carId) {
                deptName = row.car.carType
              }
              return deptName || ''
            },
            minWidth: '142px'
          },
          {
            label: 'RFID',
            formatter(row, col, cell) {
              let rfid = ''
              if (row.carId) {
                rfid = row.car.rfid
              }
              return rfid || ''
            }
          },
          {
            label: '车牌',
            formatter(row, col, cell) {
              let number = ''
              if (row.carId) {
                number = row.car.plateNumber
              }
              return number || ''
            },
            minWidth: '116px'
          },
          {
            label: '所在位置',
            formatter(row, col, cell) {
              return row.baseStation ? row.baseStation.area.name : row.autoGate.name
            },
             minWidth: '162px'
          },
          {
            label: '进场时间',
            formatter(row, col, cell) {
              return parseTime(new Date(row.enterTime).getTime())
            },
            minWidth: '162px'
          },
          {
            label: '更新时间',
            formatter(row, col, cell) {
              return parseTime(new Date(row.updateTime).getTime())
            },
            minWidth: '162px'
          },
          {
            label: '本次进场时长',
            formatter(row, col, cell) {
              let date1 = new Date() //开始时间
              let date2 = new Date(row.enterTime) //结束时间
              let date3 = date1.getTime() - new Date(date2).getTime() //时间差的毫秒数

              //计算出相差天数
              let days = Math.floor(date3 / (24 * 3600 * 1000))

              //计算出小时数
              let leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
              let hours = Math.floor(leave1 / (3600 * 1000))

              //计算相差分钟数
              let leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
              let minutes = Math.floor(leave2 / (60 * 1000))

              return (days ? days + '天 ' : '') + hours + '小时 ' + minutes + '分钟'
            },
            minWidth: '161px'
          },
          { label: '操作', custom: 'col1', minWidth: '126px' }
        ]
      }
    },
    computed: {
      ...mapGetters(['gateSwaitch'])
    },
    mounted() {
      var that = this
      // 定时更新列表
      this.timeId = setInterval(() => {
        that.isTimer = true
        let data = JSON.parse(localStorage.getItem('serchData'))
        // 有值调用查询
        this.getList(data)
      }, 1000 * 5)
    },
    beforeDestroy() {
      clearInterval(this.timeId)
    },
    methods: {
      // 请求列表数据
      async getList(query) {
        if (this.isTimer == false) {
          this.tableLoading = true
        }
        try {
          let obj = query || { pageIndex: 1, pageSize: 10, orderBy: 'updatedTime', orderByAscent: false, search: [] }
          obj.orderBy = 'updatedTime'
          obj.orderByAscent = false
          // 如果没有search，添加一个，以免报错
          if (!obj.search) {
            obj.search = []
          }
          if (this.gateSwaitch === '不展示') {
            if (obj.search.length === 0) {
              obj.search = [
                {
                  key: 'autoGateId',
                  value: 2,
                  operation: 0
                }
              ]
            } else {
              if (!obj.search.some(r => r.key == 'autoGateId')) {
                obj.search.push({
                  key: 'autoGateId',
                  value: 2,
                  operation: 0
                })
              }
            }
          } else {
            if (obj.search.length === 0) {
              obj.search = []
            } else {
              let i = query.search.findIndex(item => {
                return item.key == 'autoGateId'
              })
              if (i > -1) {
                query.search.splice(i, 1)
              }
            }
          }
          // 如果不展示闸机数据，需设置值为null
          obj.search.forEach((edit, index) => {
            if (edit.key === 'autoGateId' && edit.value === 2) {
              edit.value = null
            } else if (edit.key === 'baseStation.area.id' && edit.value === '空') {
              edit.value = null
            }
          })
          // 添加人员为空
          if (!obj.search.some(r => r.key == 'EmployeeId')) {
            obj.search.push({
              key: 'EmployeeId',
              value: null,
              Operation: 0,
              relationship: 0,
              sequence: 0
            })
          }
          // 删除车辆为空
          var find = obj.search.find(r => r.key == 'CarId')
          if (find) {
            obj.search.splice(obj.search.indexOf(find), 1)
          }
          // 如果展示闸机数据，删除这个查询条件
          let findOne = obj.search.find(k => k.key == 'autoGateId' && k.value === 1)
          if (findOne) {
            obj.search.splice(obj.search.indexOf(findOne), 1)
          }
          obj.select = this.listTitle
          // 保存查询数据
          localStorage.setItem('serchData', JSON.stringify(obj))
          // 查询
          const {
            data: { items: resData, count, pageIndex }
          } = await realtimeLocation('post', obj, false)


          this.$nextTick(() => {
            this.tableData = []
            resData.forEach(item => {
              item.loadingEdit = false
              item.loadingDel = false
              // if (item.employeeId) {
              //   this.tableData.push(item)
              // }
            })
            this.tableData = JSON.parse(JSON.stringify(resData))
            this.$refs['RefListTable'].update({ page: pageIndex, count })
            this.tableLoading = false
          })
        } catch (err) {
          this.tableLoading = false
          this.tableData = []
        }
      },
      async delRowReq(row) {
        try {
          const obj = { id: row.carId, value: null }
          await clearPeople(obj)
          row.loadingDel = false
          this.getList(this.serchObj)
          this.$message({
            type: 'success',
            message: '操作成功'
          })
        } catch (err) {
          row.loadingDel = false
          this.$message.error('操作失败！')
        }
      },
      handleRowDel(row) {
        row.loadingDel = true
        this.$_showConfirm(
          '进行手动清理',
          () => {
            this.delRowReq(row)
          },
          () => {
            row.loadingDel = false
          }
        )
      }
    }
  }
</script>
